﻿

CREATE proc [timer].[SaveTimerFile]
@FileName nvarchar(450),
@SetDate datetime2(7),
@TimerCount int,
@UserID int
as
begin
	declare @errorMsg nvarchar(150),
			@logDate datetime2(7)

	if @FileName is null
	begin
		set @errorMsg = '@FileName is null or empty.'
		goto WithError
	end

	

	begin tran

	;with sel as
	(
		select	@FileName	'FileName',
				@SetDate	'SetDate',
				@TimerCount	'TimerCount',
				@UserID		'UserID'
	) 

	merge into timer.hlpTimer as t
	using sel as s on
		s.[FileName] = t.[FileName]
		and s.UserID = t.UserID
		when not matched by target then
		insert (
				[FileName],
				SetDate,
				TimerCount,
				UserID
				)
	values	(	
				s.[FileName],
				s.SetDate,
				s.[TimerCount],
				s.UserID
			)
	when matched then
	update set
			SetDate		= s.SetDate,
			TimerCount	= s.TimerCount
			;
							
	commit

	return 0

WithError:
	if @@TRANCOUNT != 0
	begin
		rollback tran
	end
	RAISERROR
    (@errorMsg,
    10, -- Severity.
    1, -- State.
    @UserID, -- First substitution argument.
    @FileName); -- Second substitution argument. 
	return -1 
end